from flask import Flask, request, jsonify
from flask_cors import CORS
from openai import OpenAI
import spacy
import hanlp

# 初始化 Flask 应用
app = Flask(__name__)
CORS(app)

# 初始化 HanLP 和 spaCy
hanlp_analyzer = hanlp.load(hanlp.pretrained.dep.CTB9_DEP_ELECTRA_SMALL)
nlp = spacy.load("en_core_web_sm")

# 初始化 OpenAI (GLM) 客户端
client = OpenAI(
    api_key="514c84d600d7448bb9c81cbba77ae28c.E5aMEcijkvLR2Ux1",
    base_url="https://open.bigmodel.cn/api/paas/v4/"
)

# 判断是否为长句
def is_long_sentence(text, lang='zh'):
    return len(text.split()) > 20 if lang == 'en' else len(text) > 40

# 英语语法结构提取
def extract_english_syntax(text):
    doc = nlp(text)
    syntax_features = []

    for token in doc:
        # 识别从句类型
        if token.dep_ == 'ccomp' or token.dep_ == 'xcomp':
            syntax_features.append("宾语从句")
        elif token.dep_ == 'advcl':
            syntax_features.append("状语从句")
        elif token.dep_ == 'acl' or token.dep_ == 'relcl':
            syntax_features.append("定语从句")
        elif token.dep_ == 'attr':
            syntax_features.append("表语从句")
        elif token.dep_ == 'appos':
            syntax_features.append("同位语从句")
        elif token.dep_ == 'nsubj' and any(child.dep_ == 'mark' and child.text.lower() in ['that', 'whether'] for child in token.children):
            syntax_features.append("主语从句")

        # 分词结构识别
        if token.tag_ in ['VBG', 'VBN']:
            syntax_features.append("分词结构：" + token.text)

        # 被动语态
        if token.dep_ == 'nsubjpass':
            syntax_features.append("被动语态")

    if len(list(doc.sents)) > 1:
        syntax_features.append("复合句")
    if is_long_sentence(text, 'en'):
        syntax_features.append("长句")

    return list(set(syntax_features))


# 中文语法结构提取
def extract_chinese_syntax(text):
    parsed = hanlp_analyzer(text)
    syntax_features = []
    if is_long_sentence(text, 'zh'):
        syntax_features.append("长句")
    if isinstance(parsed, list) and len(parsed) > 0:
        deprels = [dep for sent in parsed for dep in sent['deprel']]
        if '定中关系' in deprels:
            syntax_features.append("定语结构")
        if '状中结构' in deprels:
            syntax_features.append("状语结构")
        if '主谓关系' in deprels:
            syntax_features.append("主谓结构")
    return list(set(syntax_features))

# 翻译技法判断
def judge_translation_technique(orig_syntax, trans_syntax):
    shared = set(orig_syntax) & set(trans_syntax)
    if len(shared) / max(len(set(orig_syntax + trans_syntax)), 1) > 0.5:
        return ["直译"]
    else:
        return ["意译"]

# 翻译调用大模型（英文翻译成中文）
def translate_with_glm(text):
    try:
        prompt = f"请将下面这句英文翻译成中文：\n{text}"
        completion = client.chat.completions.create(
            model="glm-4",
            messages=[
                {"role": "user", "content": prompt},
            ],
            top_p=0.7,
            temperature=0.9
        )
        translation = completion.choices[0].message.content.strip()
        return translation
    except Exception as e:
        return f"翻译出错: {str(e)}"